import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "@/store/user";

const routes = [
  {
    path: "/",
    component: () => import("@/views/Layout.vue"),
    children: [
      {
        path: "/",
        name: "home",
        component: () => import("@/views/home/index.vue"),
      },
      {
        path: "/category/:id",
        name: "category",
        component: () => import("@/views/category/index.vue"),
      },
      {
        path: "/category/sub/:id",
        name: "sub",
        component: () => import("@/views/category/sub.vue"),
      },
      {
        path: "/product/:id",
        name: "product",
        component: () => import("@/views/product/index.vue"),
      },
      {
        path: "/cart",
        name: "cart",
        component: () => import("@/views/cart/index.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "/member/checkout",
        name: "checkout",
        component: () => import("@/views/member/pay/checkout.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "/member/pay",
        name: "pay",
        component: () => import("@/views/member/pay/index.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "/member/result",
        name: "result",
        component: () => import("@/views/member/pay/result.vue"),
        meta: {
          requireAuth: true,
        },
      },
    ],
  },
  {
    path: "/member",
    component: () => import("@/views/member/Layout.vue"),
    children: [
      {
        path: "/member",
        name: "member-home",
        component: () => import("@/views/member/home/index.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(), // 路由模式
  routes, // 路由规则
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { left: 0, top: 0 };
  },
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  if (from.name == "Login") {
    // 如果不需要权限校验，直接进入路由界面
    next();
  } else if (to.meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (userStore.token) {
      // 获取当前的token是否存在
      next();
    } else {
      next({
        path: "/login", // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: { redirect: to.fullPath },
      });
    }
  } else {
    // 如果不需要权限校验，直接进入路由界面
    next();
  }
});

router.afterEach(() => {});

export default router;
